Create Project: springboot_csrf_token_application (add Spring Boot Starters from the table)
Edit File: application.properties (add Role, User, Password)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside package controllers)
application.properties
# SECURITY
spring.security.user.name = myuser
spring.security.user.password = mypassword
spring.security.user.roles = USER
MyController.java
package com.ivoronline.springboot_csrf_token_application.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping("/HelloForm")
public String helloForm() {
return "HelloForm";
}
@ResponseBody
@RequestMapping("/SayHello")
public String sayHello(@RequestParam String name) {
return "Hello " + name;
}
}
HelloForm.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<title> HELLO FORM </title>
<style type="text/css">
div { display:flex; flex-direction:column; align-items:center; border: solid 1pt; margin: 10pt 50pt;
background-color: aliceblue }
</style>
<div>
<h2> HELLO FORM </h2>
<form method="GET" action="SayHello">
<p> <input type="text" name="name" placeholder="Enter your name"/> </p>
<p> <input type="submit" name="submit" style="width:100%" /> </p>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
</form>
</div>
<html>